#include "AddWholeBodyDynamicHandlerDialog.h"
#include "ui_AddWholeBodyDynamicHandlerDialog.h"

#include "../WholeBodyDynamicCalculator.h"
#include <QCheckBox>
#include <QMessageBox>
#include <set>

AddWholeBodyDynamicHandlerDialog::AddWholeBodyDynamicHandlerDialog(QWidget* parent, MMM::MotionList motions) :
    QDialog(parent),
    ui(new Ui::AddWholeBodyDynamicHandlerDialog),
    motions(motions),
    currentMotion(nullptr),
    allMotion(true),
    calculated(false)
{
    ui->setupUi(this);

    loadMotions();

    connect(ui->AllMotionCheckBox, SIGNAL(toggled(bool)), this, SLOT(allMotionToggled(bool)));
    connect(ui->ChooseMotionGroupBox, SIGNAL(toggled(bool)), this, SLOT(chooseMotionToggled(bool)));
    connect(ui->ChooseMotionGroupBox, SIGNAL(toggled(bool)), ui->ChooseMotionComboBox, SLOT(setEnabled(bool)));
    connect(ui->ChooseMotionComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(setCurrentMotion(int)));
    connect(ui->CalculateButton, SIGNAL(clicked()), this, SLOT(calculate()));
    connect(ui->CancelButton, SIGNAL(clicked()), this, SLOT(close()));
}

AddWholeBodyDynamicHandlerDialog::~AddWholeBodyDynamicHandlerDialog() {
    delete ui;
}

bool AddWholeBodyDynamicHandlerDialog::calculateWholeBodyDynamic() {
    exec();
    return calculated;
}

void AddWholeBodyDynamicHandlerDialog::loadMotions() {
    for (MMM::MotionPtr motion : motions) {
        ui->ChooseMotionComboBox->addItem(QString::fromStdString(motion->getName()));
    }
    setCurrentMotion(0);
}

void AddWholeBodyDynamicHandlerDialog::setCurrentMotion(int index) {
    if (index >= 0 && motions.size() > static_cast<std::size_t>(index)) {
        currentMotion = motions[index];
    }
}

void AddWholeBodyDynamicHandlerDialog::chooseMotionToggled(bool checked) {
    ui->AllMotionCheckBox->setChecked(!checked);
    allMotion = !checked;
}

void AddWholeBodyDynamicHandlerDialog::allMotionToggled(bool checked) {
    ui->ChooseMotionGroupBox->setChecked(!checked);
    allMotion = checked;
}

void AddWholeBodyDynamicHandlerDialog::calculate() {
    if (allMotion) {
        for (MMM::MotionPtr motion : motions) {
            MMM::WholeBodyDynamicCalculator::calculate(motion);
        }
    } else {
        MMM::WholeBodyDynamicCalculator::calculate(currentMotion);
    }
    calculated = true;
    this->close();
}
